import { defineStore } from "pinia";
import { ref } from "vue";

export interface Playlist {
  id: string;
  name: string;
  cover?: string;
  songCount?: number;
  description?: string;
  category?: string;
  musicIds?: number[];
}

export const usePlaylistStore = defineStore("playlist", () => {
  // 状态
  const userPlaylists = ref<Playlist[]>([]);
  const favoritePlaylists = ref<Playlist[]>([]);

  // 更新用户创建的歌单
  const setUserPlaylists = (playlists: Playlist[]) => {
    userPlaylists.value = playlists;
  };

  // 更新收藏的歌单
  const setFavoritePlaylists = (playlists: Playlist[]) => {
    favoritePlaylists.value = playlists;
  };

  // 添加新歌单
  const addUserPlaylist = (playlist: Playlist) => {
    userPlaylists.value.push(playlist);
  };

  // 移除歌单
  const removeUserPlaylist = (playlistId: string) => {
    userPlaylists.value = userPlaylists.value.filter(
      (playlist) => playlist.id !== playlistId
    );
  };

  // 添加收藏歌单
  const addFavoritePlaylist = (playlist: Playlist) => {
    favoritePlaylists.value.push(playlist);
  };

  // 取消收藏歌单
  const removeFavoritePlaylist = (playlistId: string) => {
    favoritePlaylists.value = favoritePlaylists.value.filter(
      (playlist) => playlist.id !== playlistId
    );
  };

  // 添加歌曲到用户歌单
  const addSongToUserPlaylist = (playlistId: string, songId: number) => {
    const playlist = userPlaylists.value.find((p) => p.id === playlistId);
    if (playlist && playlist.musicIds && !playlist.musicIds.includes(songId)) {
      playlist.musicIds.push(songId);
      playlist.songCount = (playlist.songCount || 0) + 1;
    }
  };

  return {
    userPlaylists,
    favoritePlaylists,
    setUserPlaylists,
    setFavoritePlaylists,
    addUserPlaylist,
    removeUserPlaylist,
    addFavoritePlaylist,
    removeFavoritePlaylist,
    addSongToUserPlaylist,
  };
});
